package com.wangxiaonan.wxwork.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wangxiaonan.wxwork.domain.Agent;
import com.wangxiaonan.wxwork.domain.Appchat;
import com.wangxiaonan.wxwork.exeption.ServiceException;
import com.wangxiaonan.wxwork.service.AgentService;
import com.wangxiaonan.wxwork.service.AppChatService;
import com.wangxiaonan.wxwork.service.TokenService;
import com.wangxiaonan.wxwork.util.IDUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 群聊管理接口
 *
 * @Author: wangxiaonan
 * @Date: 2018/8/22
 **/
@RestController
@RequestMapping("/appchat")
public class AppChatController {
    private static final String AGENT_TOKEN_KEY = "agent_";

    @Resource
    private AppChatService appChatService;
    @Resource
    private TokenService tokenService;
    @Resource
    private AgentService agentService;

    @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getAppChat(@PathVariable(value = "id") String chatId) {
        JSONObject rs = new JSONObject();
        rs.put("status", "ok");

        Appchat appchat = appChatService.queryById(chatId);
        if (appchat == null) {
            rs.put("status", "fail");
            rs.put("msg", "not found");
            return rs.toJSONString();
        }

        Agent agent = agentService.queryAgentById(appchat.getAgentId());
        if (agent == null) {
            rs.put("status", "fail");
            rs.put("msg", "not found agent");
            return rs.toJSONString();
        }
        String token;
        try {
            token = tokenService.getTokenString(agent.getCorpId(), agent.getSecret());
        } catch (ServiceException se) {
            rs.put("status", se.getCode());
            rs.put("msg", se.getMsg());
            return rs.toJSONString();
        }

        JSONObject jsonObject = appChatService.getAppChat(token, chatId);

        rs.put("data", jsonObject);
        return rs.toJSONString();
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getAppChatList(@RequestParam(value = "agent_id") String agentId) {
        JSONObject rs = new JSONObject();
        rs.put("status", "ok");

        List<Appchat> appChats = appChatService.queryByAgentId(agentId);

        rs.put("data", appChats);
        return rs.toJSONString();
    }

    @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String createAppChat(@RequestBody String chatParam, @RequestParam(value = "agent_id") String agentId) {
        JSONObject rs = new JSONObject();
        rs.put("status", "ok");

        Agent agent = agentService.queryAgentById(agentId);
        if (agent == null) {
            rs.put("status", "fail");
            rs.put("msg", "not found agent");
            return rs.toJSONString();
        }
        JSONObject chatJson = JSONObject.parseObject(chatParam);
        String chatId = chatJson.getString("chatid");
        if (StringUtils.isBlank(chatId)) {
            chatJson.put("chatid", IDUtil.getUUID32());
        }
        JSONArray userList = chatJson.getJSONArray("userlist");
        if (userList.size() < 2 || userList.size() > 500) {
            rs.put("status", "fail");
            rs.put("msg", "userList at least 2 people, up to 500 people");
            return rs.toJSONString();
        }
        //  String name = chatJson.getString("chatJson");
        //  if (StringUtils.isBlank(name)) {
        //      chatJson.put("name","");
        //  }

        String token;
        try {
            token = tokenService.getTokenString(agent.getCorpId(), agent.getSecret());
        } catch (ServiceException se) {
            rs.put("status", se.getCode());
            rs.put("msg", se.getMsg());
            return rs.toJSONString();
        }
        Appchat appChat = new Appchat();
        appChat.setAgentId(agentId);
        appChat.setChatId(chatJson.getString("chatid"));
        appChat.setChatName(chatJson.getString("name"));
        try {
            JSONObject result = appChatService.saveAndCreateAppChat(appChat, token, chatJson.toJSONString());
            rs.put("data", result);
        } catch (Exception e) {
            rs.put("msg", e.getMessage());
            rs.put("status", "fail");
        }

        return rs.toJSONString();
    }

    @RequestMapping(value = "/message", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String sendChatMessage(@RequestParam(value = "agent_id") String agentId, @RequestBody String msgBody) {
        JSONObject rs = new JSONObject();
        rs.put("status", "ok");
        Agent agent = agentService.queryAgentById(agentId);
        if (agent == null) {
            rs.put("status", "agent_not_exists");
            return rs.toJSONString();
        }

        String token;
        try {
            token = tokenService.getTokenString(agent.getCorpId(), agent.getSecret());
        } catch (ServiceException se) {
            rs.put("status", se.getCode());
            rs.put("msg", se.getMsg());
            return rs.toJSONString();
        }

        try {
            JSONObject jsonObject = appChatService.sendMessage(token, msgBody);
            if ("0".equals(jsonObject.getString("errcode"))) {
                rs.put("data", jsonObject);
            } else {
                rs.put("status", "retry");
                rs.put("msg", jsonObject);
            }
        } catch (Exception e) {
            rs.put("status", "chat_send_fail");
            return rs.toJSONString();
        }

        return rs.toJSONString();
    }

}
